// pages/confirmOrder/confirmOrder.js
Page({
  data: {
    orderObj: {},
    layerFlage: 1,
    wxtsflage: 1,
    qstsflage: 1,
    pssjflage: 1,
    isOto: false,
    useCoupon: 1,
    couponId: '',
    addressId: "",
    supmarketName: "",
    supNarketAddress: "",
    //自提相关
    phone: "",
    //配送时间
    deliveryDateName: "",
    deliveryTimeInterval: "",
    deliveryDate: "",
    deliveNow: "",
    dataindex: 0,
    otoflage: false,
    invoice_type: 0,
    invoice_title: "个人",
    invoice_num: "",
    invoice_contect: "",
    out_of_stock_notes: [],
    out_of_stock_notes_str: "",
    notes: "",
    //确认订单锁
    corderflage:1
  },
  onLoad: function (options) {
    var otoflage = options.otoflage;
    var phone = options.phone;
    if (otoflage == "true") {
      this.setData({
        isOto: true,
        phone: phone
      })
    } else {
      if (phone == undefined ){
        this.setData({
          isOto: false
        })
      }else{
        this.setData({
          isOto: false,
          phone: phone
        })
      }
     
    }
    this.setTapList();
  },
  onShow: function () {
    //是否使用优惠券
    if (wx.getStorageSync('orderObj').coupons == undefined) {
      this.setData({
        useCoupon: 1
      })
    } else {
      this.setData({
        useCoupon: 0,
        cashid: wx.getStorageSync('orderObj').coupons.id
      })
    }
    this.setData({
      supmarketName: wx.getStorageSync('supername'),
      supmarketAddress: wx.getStorageSync('superaddress')
    })
    this.getOrderInfo();
  },
  //重新获取订单信息
  setOrderInfor() {
    var body = {};
    body.address_id = wx.getStorageSync('addressId');
    body.supermarket_id = wx.getStorageSync('supermarket_id');
    body.use_coupon = this.data.useCoupon;
    body.is_o2o = this.data.isOto;
    console.log(body)
    var url = getApp().data.url + 'order/settlementOrderInfo';
    getApp().wxAjax(this.setOriderSug, url, body);
  },
  setOriderSug(res) {
    var resObj = res.data;
    if (resObj.header.res_code == 0 || resObj.header.res_code == 6001008 || resObj.header.res_code == 6001006) {
      wx.setStorageSync('orderObj', resObj.body);
      this.getOrderInfo();
    } else {
      console.log(resObj)
      wx.showToast({
        title: resObj.header.message,
        icon: 'none'
      })
    }
  },
  //设置订单页面信息
  getOrderInfo(res) {
    var orderObj = wx.getStorageSync('orderObj');
    //优惠券金额
    var useCashInfoValue;
    if (orderObj.coupons == undefined) {
      useCashInfoValue = '';
    } else {
      useCashInfoValue = orderObj.coupons.value;
    }
    //优惠券列表
    var useableList = [];
    if (typeof orderObj.useable_list == 'undefined') {
      useableList = []
    } else {
      useableList = orderObj.useable_list;
    }
    //收货地址列表
    var addressList = [];
    if (typeof orderObj.address == 'undefined') {
      addressList = [];
    } else {
      addressList = orderObj.address;
    }

    this.setData({
      orderObj: orderObj,
      addressList: addressList,
      goodsList: orderObj.order_info.skulist,
      consumptionDescs: orderObj.consumption_descs,
      useableList: useableList,
      useCashInfoValue: useCashInfoValue,
      formToken: orderObj.form_token,
    })

    if (orderObj.out_of_stock_notes != undefined) {
      this.setData({
        out_of_stock_notes: orderObj.out_of_stock_notes,
        out_of_stock_notes_str: orderObj.out_of_stock_notes[0].config_item_name
      })
    }
    console.log(this.data.orderObj)
    this.setDeliveryTime();
  },
  //设置配送时间
  setDeliveryTime() {
    var orderObj = this.data.orderObj;
    var deliveryTimeList = this.data.orderObj.delivery_time;

    for (let i = 0; i < deliveryTimeList.length; i++) {
      for (let j = 0; j < deliveryTimeList[i].delivery_time_interval.length; j++) {
        if (i == 0 && j == 0) {
          this.setData({
            deliveryDateName: deliveryTimeList[i].delivery_date_name,
            deliveryDate: deliveryTimeList[i].delivery_date,
            deliveNow: deliveryTimeList[i].delivery_time_interval[j],
            deliveryTimeInterval: deliveryTimeList[i].delivery_time_interval[j].time_interval
          })
          var name = deliveryTimeList[i].delivery_time_interval[j].name;
          if (name == undefined) {
            this.setData({
              deliveNow: ''
            })
          } else {
            this.setData({
              deliveNow: name
            })
          }
        }
      }

    }

    //构建数组
    var myleftlist = [];
    var myrightlist = [];
    for (let i = 0; i < deliveryTimeList.length; i++) {
      var obj = {};
      obj.delivery_date = deliveryTimeList[i].delivery_date;
      obj.delivery_date_name = deliveryTimeList[i].delivery_date_name;
      obj.select = 0;
      if (i == 0) {
        obj.select = 1;
      }
      var obj2 = {};
      obj2.select = 0;
      if (i == 0) {
        obj2.select = 1;
      }
      for (let j = 0; j < deliveryTimeList[i].delivery_time_interval.length; j++) {
        deliveryTimeList[i].delivery_time_interval[j].freight = orderObj.freight + '元配送费';
        deliveryTimeList[i].delivery_time_interval[j].delivery_date = deliveryTimeList[i].delivery_date;
        deliveryTimeList[i].delivery_time_interval[j].delivery_date_name = deliveryTimeList[i].delivery_date_name;
        deliveryTimeList[i].delivery_time_interval[j].select = 0;
        if (i == 0 && j == 0) {
          deliveryTimeList[i].delivery_time_interval[j].select = 1;
        }

      }
      obj2.delivery_time_interval = deliveryTimeList[i].delivery_time_interval;
      myleftlist.push(obj)
      myrightlist.push(obj2)
    }
    this.setData({
      myleftlist: myleftlist,
      myrightlist: myrightlist
    })
  },
  changePssj() {
    this.setData({
      layerFlage: 0,
      pssjflage: 0,
    })
  },
  //切换日期
  tabDate(e) {
    var index = e.currentTarget.dataset.index;
    var myleftlist = this.data.myleftlist;
    var myrightlist = this.data.myrightlist;
    for (let i = 0; i < myrightlist.length; i++) {
      myrightlist[i].select = 0;
      if (index == i) {
        myrightlist[i].select = 1;
      }
    }
    for (let i = 0; i < myleftlist.length; i++) {
      myleftlist[i].select = 0;
      if (index == i) {
        myleftlist[i].select = 1;
      }
    }
    this.setData({
      myleftlist: myleftlist,
      myrightlist: myrightlist,
      dataindex: index
    })

  },
  //切换时间
  tabTime(e) {
    var dateIndex = this.data.dataindex;
    var index = e.currentTarget.dataset.index;
    var date = e.currentTarget.dataset.date;
    var dataname = e.currentTarget.dataset.datename;
    var time = e.currentTarget.dataset.time;
    var deliveNow = e.currentTarget.dataset.now;
    var myrightlist = this.data.myrightlist;
    console.log(dateIndex, index)
    if (deliveNow == undefined) {
      deliveNow = ''
    }
    for (let i = 0; i < myrightlist.length; i++) {
      for (let j = 0; j < myrightlist[i].delivery_time_interval.length; j++) {
        myrightlist[i].delivery_time_interval[j].select = 0;
      }
      myrightlist[dateIndex].delivery_time_interval[index].select = 1;
    }
    this.setData({
      myrightlist: myrightlist,
      deliveryTimeInterval: time,
      deliveryDate: date,
      deliveryDateName: dataname,
      deliveNow: deliveNow
    })
    this.hideLayer();
  },
  //变换配送方式
  changeDistribution(e) {
    var dStatus = e.currentTarget.dataset.oto;
    var index = e.currentTarget.dataset.index;
    var tapList = this.data.tapList;
    for (let i = 0; i < tapList.length; i++) {
      tapList[i].select = 0;
      if (index == i) {
        tapList[i].select = 1;
      }
    }
    if (dStatus == 1) {
      dStatus = false;
    } else {
      dStatus = true;
    }
    this.setData({
      isOto: dStatus,
      tapList: tapList
    })
    this.setOrderInfor();
  },
  //获得手机号
  getPhone(e) {
    var phone = e.detail.value;
    this.setData({
      phone: phone
    })
  },
  //确认下单
  confirmOrder() {
    var me = this;
    var orderObj = this.data.orderObj;
    if (orderObj.payable_amount < orderObj.allow_sell_amount) {
      this.setData({
        layerFlage: 0,
        qstsflage: 0
      })
    } else {
      var isOto = this.data.isOto;
      console.log(isOto)
      if (isOto) {
        wx.showModal({
          title: '',
          confirmText: "确认",
          cancelColor: "#999",
          content: '确定前往【' + wx.getStorageSync("supername") + '】自提？',
          success: function (res) {
            if (res.confirm) {
              me.submitOrider();
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        var address_id = wx.getStorageSync("addressId");
        if (address_id == "") {
          wx.showModal({
            title: '',
            confirmText: "确认",
            cancelColor: "#999",
            content: '请先添加收货地址',
            success: function (res) {
              if (res.confirm) {
                me.toAddAddress();
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          this.submitOrider();
        }

      }

    }
  },
  submitOrider() {
    var url = getApp().data.url + 'order/submitOrder';
    var body = {};
    var is_o2o = this.data.isOto;
    var use_coupon = this.data.useCoupon;
    body.address_id = wx.getStorageSync("addressId");
    body.is_o2o = is_o2o;
    //发票
    body.invoice_type = this.data.invoice_type;
    body.invoice_title = this.data.invoice_title;
    body.invoice_num = this.data.invoice_num;
    body.invoice_contect = this.data.invoice_contect;
    //留言
    body.out_of_stock_notes = this.data.out_of_stock_notes_str;
    body.notes = this.data.notes;

    body.use_coupon = use_coupon;
    body.supermarket_id = wx.getStorageSync('supermarket_id');
    body.form_token = this.data.formToken;
    body.delivery_time_interval = this.data.deliveryTimeInterval;
    body.delivery_date = this.data.deliveryDate;
    if (is_o2o) {
      var phone = this.data.phone;
      console.log(phone)
      var telRule = /^1[3|4|5|7|8]\d{9}$/,
        nameRule = /^[\u2E80-\u9FFF]+$/;
      if (phone == undefined) {
        wx.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return false;
      } else {
        if (!telRule.test(phone)) {
          wx.showToast({
            title: '手机号码格式不正确',
            icon: 'none'
          })
          return false;
        } else {
          body.user_mobile = phone;
        }
      }
    }
    if (use_coupon == 0) {
      body.coupon_id = this.data.cashid;
    }
    var url = getApp().data.url + 'order/submitOrder';
    var corderflage = this.data.corderflage;
    if(corderflage == 1){
      this.setData({
        corderflage:2
      })
      getApp().wxAjax(this.submitSug, url, body);
    }
   
    console.log(body)
  },
  submitSug(res) {
    var resObj = res.data;
    this.setData({
      corderflage: 1
    })
    if (resObj.header.res_code == 0) {
      wx.redirectTo({
        url: '../payset/payset?order_id=' + resObj.body.order_id,
      })
      console.log(resObj)
    } else {
      console.log(res)
      wx.showToast({
        title: resObj.header.message,
        icon: 'none'
      })
    }
  },
  toCanuseCash() {
    // wx.redirectTo({
    //   url: '../canusecash/canusecash?isoto=' + this.data.isOto,
    // })
    wx.navigateTo({
      url: '../canusecash/canusecash?isoto=' + this.data.isOto + '&phone=' + this.data.phone,
    })
  },
  //前往地址列表
  toaddressList() {
    wx.navigateTo({
      url: '../addressList/addressList?form=corder',
    })
  },
  showWxts() {
    this.setData({
      wxtsflage: 0,
      layerFlage: 0
    })
  },
  hideLayer() {
    this.setData({
      wxtsflage: 1,
      qstsflage: 1,
      layerFlage: 1,
      pssjflage: 1,
    })
  },
  toAddAddress() {
    wx.setStorageSync('fromFlage', 'corder')
    wx.navigateTo({
      url: '../addAddress/addAddress?pageFrom=corder'
    })
  },

  setTapList() {
    var tapList = [
      { title: "送货上门", select: 1, oto: "1" },
      { title: "店内自提", select: 0, oto: "2" },
    ];
    this.setData({
      tapList: tapList
    })
  },

  toInvoice() {
    var invoice_type = this.data.invoice_type,
      invoice_title = this.data.invoice_title,
      invoice_num = this.data.invoice_num,
      invoice_contect = this.data.invoice_contect;
    wx.navigateTo({
      url: '../invoice/invoice?invoice_type=' + invoice_type + "&invoice_title=" + invoice_title + "&invoice_num=" + invoice_num + "&invoice_contect=" + invoice_contect,
    })
  },

  toRemarks() {
    var notes = this.data.notes;
    wx.navigateTo({
      url: '../remarks/remarks?notes=' + notes,
    })

  },

  openOut: function () {
    this.setData({
      layerFlage: 0,
      outflage: 0,
    })
  },

  checkOut(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      out_of_stock_notes_str: this.data.out_of_stock_notes[index].config_item_name
    })

    this.hideLayer();
    this.setData({
      outflage: 1
    })

  },

  checkQOut() {
    this.hideLayer();
    this.setData({
      outflage: 1
    })
  },
})